# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: shell_timer.py 
@time: 2019/8/2 下午2:26
@note:
写一个计时器
"""
import time

class Timer:

    def __init__(self, func=time.perf_counter):

        self.elapsed = 0.0
        self._func = func
        self._start = None

    def start(self):

        if self._start is not None:
            raise RuntimeError('Already started')
        self._start = self._func()

    def stop(self):

        if self._start is None:
            raise RuntimeError('Not started')
        end = self._func()
        self.elapsed += end - self._start
        self._start = None

    def reset(self):

        self.elapsed = 0.0

    @property
    def running(self):

        return self._start is not None

    def __enter__(self):

        self.start()
        return self

    def __exit__(self, *args):

        self.stop()


def counttimes(n):

    while n > 0:
        n -= 1


# Example usage
'示例1 Timer 类记录的时间是钟表时间，并包含了所有休眠时间'
t = Timer()
t.start()
counttimes(10000000)
t.stop()
print(t.elapsed)

t.reset()
with t:
    counttimes(10000000)
print(t.elapsed)

'示例2 只想计算该进程所花费的 CPU 时间，应该使用 time.process_time() 来代替'
with Timer(time.process_time) as t2:
    counttimes(10000000)
print(t2.elapsed)

with t2:
    counttimes(10000000)
print(t2.elapsed)